package cn.hj.domain.strategy.service.Armory;

import cn.hj.domain.strategy.adapter.repository.IStrategyRepository;
import cn.hj.domain.strategy.model.entity.StrategyAwardEntity;
import cn.hj.domain.strategy.model.entity.StrategyEntity;
import cn.hj.domain.strategy.model.entity.StrategyRuleEntity;
import cn.hj.types.common.Constants;
import cn.hj.types.enums.ResponseCode;
import cn.hj.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/*
 * 策略装配实现类
 * */
@Primary
@Service
@Slf4j
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {

    @Resource
    private IStrategyRepository strategyRepository;



    @Override
    public boolean assembleLotteryStrategy(long strategyId) {
        //查询策略配置
        List<StrategyAwardEntity> strategyAwardEntities = strategyRepository.queryStrategyAwardList(strategyId);
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);

        //缓存奖品库存（用于decr扣减库存使用）
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCount = strategyAwardEntity.getAwardCount();
            cacheStrategyAwardCount(awardId,awardCount,strategyId);
        }

        //权重策略配置-适用于rule_weight 权重规则配置
        StrategyEntity strategy = strategyRepository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategy.getRuleWeight();
        if (ruleWeight == null) {
            return true;
        }
        // 3.2 权重策略配置 - 适用于 rule_weight 权重规则配置【4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109】
        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRuleByStrategyId(strategyId, ruleWeight);
        String ruleValue = strategyRuleEntity.getRuleValue();

        if (ruleValue == null) {
            return true;
        }
        if (null == strategyRuleEntity) {
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }

        Map<String, List<Integer>> ruleWeightValues = strategyRuleEntity.getRuleWeightValues();
        for (String key : ruleWeightValues.keySet()) {
            List<Integer> awardIds = ruleWeightValues.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(strategyAwardEntity -> !awardIds.contains(strategyAwardEntity.getAwardId()));
            assembleLotteryStrategy(strategyId + "_" + key, strategyAwardEntitiesClone);
        }
        return true;

    }

    /**
     * 根据活动id装配策略配置
     * @param activityId
     * @return
     */
    @Override
    public boolean assembleLotteryStrategyByActivityId(long activityId) {
        long strategyId = strategyRepository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    /**
     * 缓存奖品库存
     * @param awardId
     * @param awardCount
     * @param strategyId
     */
    private void cacheStrategyAwardCount(Integer awardId, Integer awardCount,Long strategyId) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        strategyRepository.cacheStrategyAwardCount(cacheKey, awardCount);
    }


    public void assembleLotteryStrategy(String key, List<StrategyAwardEntity> strategyAwardEntities) {
        //获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //获取概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);


        //用1 % 0.0001 获取概率范围，百分位、千分位、万分位
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);

        //
        ArrayList<Integer> strategyAwrdSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            //计算出每个概率值需要存放到查找表的数量，循环填充
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwrdSearchRateTables.add(awardId);
            }
        }

        //乱序
        Collections.shuffle(strategyAwrdSearchRateTables);

        //
        HashMap<Integer, Integer> shuffleStrategyAwardSearchRateTables = new HashMap<>();
        for (int i = 0; i < strategyAwrdSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTables.put(i, strategyAwrdSearchRateTables.get(i));
        }

        //存储到redis
        strategyRepository.storeStrategyAwardSearchRateTables(key, rateRange, shuffleStrategyAwardSearchRateTables);
    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        int range = strategyRepository.getRange(strategyId);
        //通过生成的随机值，获取概率查找表的结果
        return strategyRepository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(range));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = strategyId + "_" + ruleWeightValue;
        int range = strategyRepository.getRange(Long.valueOf(key));
        return strategyRepository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(range));

    }



    /**
     * 扣减库存
     * @param strategyId 策略ID
     * @param awardId    奖品ID
     * @return 扣减结果
     */
    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId, Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return strategyRepository.subtractionAwardStock(cacheKey,endDateTime);
    }


}
